/*  File Name	: TimerTest.cpp
 *  Author		: Pang Jiacai
 *	 E-mail		: 823960168@qq.com
 *  Created on	: 2012-6-18
 *  Description:
 */
#ifndef TIMERTEST_CPP_
#define TIMERTEST_CPP_
#include "TimerTest.h"

TimerTask::TimerTask()
{

}

TimerTask::~TimerTask()
{

}

int TimerTask::open(void)
{
	return Thread::open(this,cb);
}

int TimerTask::cb(void *p)
{
	TimerTask *task = (TimerTask*)p;
	task->add_timer();
	return task->run_loop();
}

void TimerTask::add_timer()
{

}

int TimerTask::run_loop(void)
{
	while (true)
	{
		sleep(15);
		int rank = rand() % this->timer_num_+1;
		std::list<Timer>::iterator iter = timer_list.begin();
		std::list<std::list<Timer>::iterator> del_list;
		for (; iter != timer_list.end(); iter++)
		{
			if(rank >this->timer_num_/4 && rank < this->timer_num_/2 && iter->timer_id()==rank)
			{
				int i = (rand()%15+1);
				LOG((DEBUG_LOG,"----refresh timer:%d--%d--\n",rank,i));
				iter->refresh_timer(TimeValue(i));
			}
			else if(rank >=this->timer_num_/2 && iter->timer_id()==rank)
			{
				LOG((DEBUG_LOG,"----cancel timer:%d----\n",rank));
				iter->cancel_timer();
				del_list.push_back(iter);
			}
		}
		std::list<std::list<Timer>::iterator>::iterator del_iter = del_list.begin();
		for(;del_iter!=del_list.end();del_iter++)
		{
			timer_list.erase(*del_iter);
		}
		del_list.clear();

//		if(this->timer_list.size()<=0)
//		{
//			this->reactor()->end_reactor_loop();
//		}
	}
	return 0;
}

int TimerTask::timer_test(Reactor *reactor,int number)
{
	this->timer_num_ = number;
	this->reactor(reactor);

	for(int i=0;i< timer_num_;i++)
	{
		char name[100]={0};
		sprintf(name,"%s_%d","timer",(i+1));
		Timer timer(reactor,name);
		timer_list.push_back(timer);
	}
	std::list<Timer>::iterator iter = timer_list.begin();


	for(;iter!=timer_list.end();iter++)
	{
		int delay = (rand()%15)+1;
		int interval = (rand()%10)+1;
		std::cout << iter->name() <<" "<< delay <<"  "<< interval <<std::endl;
		if(iter->schedule_timer(TimeValue(delay, 0),TimeValue(interval))<=0)
		{
			std::cout << "timer schedule failed:"<< iter->name() <<std::endl;
			iter->cancel_timer();
		}
	}

	//this->open();
	//this->activate();
	return 0;
}

#endif //TIMERTEST_CPP_
